//
//  SettingViewController.m
//  iOS-CtrlV
//
//  Created by 龚 杰 on 12-12-20.
//  Copyright (c) 2012年 Wang Li. All rights reserved.
//

#import "SettingViewController.h"
#import "NicknameSetViewController.h"
#import "HeadImgSetViewController.h"
#import "MainTabBarController.h"
#import "WebViewController.h"
#import "OwnViewController.h"

#define USERHAEDPATH [NSString stringWithFormat:@"%@/tmp/haedimage.jpeg",NSHomeDirectory()]
@interface SettingViewController ()

@end

@implementation SettingViewController
@synthesize name;
@synthesize headimage;
@synthesize headurl = m_head_url;
@synthesize delegate;
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}
- (id)init
{
    if (self = [super init]) {
        isSend = NO;
        sendtype = 2;
        m_type = 0;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
   [self.view setBackgroundColor:[UIColor colorWithRed:221/250.f green:224/255.0f blue:223/255.0f alpha:1.0]];

	// Do any additional setup after loading the view.
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
	// Do any additional setup after loading the view.
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:tAppDel.m_MidNavImg forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = NO;
        
    }
    m_BackBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    m_BackBttBarItem.frame =CGRectMake(0, 0, 44, 44);
    [m_BackBttBarItem setImage:[UIImage imageNamed:@"navback.png"] forState:UIControlStateNormal];
    [m_BackBttBarItem addTarget:self action:@selector(navBackBtta) forControlEvents:UIControlEventTouchUpInside];
    [m_BackBttBarItem retain];
    [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    
    m_settngBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    m_settngBttBarItem.frame =CGRectMake(self.navigationController.navigationBar.frame.size.width-44, 0, 44, 44);
    [m_settngBttBarItem setImage:[UIImage imageNamed:@"halt.png"] forState:UIControlStateNormal];
    [m_settngBttBarItem addTarget:self action:@selector(navSettingBtt) forControlEvents:UIControlEventTouchUpInside];
    [m_settngBttBarItem retain];
    [self.navigationController.navigationBar addSubview:m_settngBttBarItem];
    
    m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                               style:UITableViewStyleGrouped];
    [m_TableView setDataSource:self];
    [m_TableView setDelegate:self];
    UIView* iview = [[UIView alloc] initWithFrame:m_TableView.frame];
    [iview setBackgroundColor:[UIColor colorWithRed:221/250.f green:224/255.0f blue:223/255.0f alpha:1.0]];
    m_TableView.backgroundView =iview;
    [iview release];
    [self.view addSubview:m_TableView];

    m_DLCImagePicker = [[DLCImagePickerController alloc] init];
    m_DLCImagePicker.delegate = self;
    m_DLCImagePicker.RootuUIViewController =self;
     m_DLCImagePicker.Size = CGSizeMake(50, 50);
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    m_userid = [tUserDef objectForKey:@"user_id"];
    m_pcode = [tUserDef objectForKey:@"privateCod"];
    m_oldname = self.name;
    m_oldhaedimg = self.headimage;
    
    m_iSwitch_SINA = [[UISwitch alloc] initWithFrame:CGRectMake(self.view.frame.size.width-120, 10, 70, 35)];
    m_iSwitch_SINA.tag = 103;
    [m_iSwitch_SINA addTarget:self action:@selector(changeiSwitch:) forControlEvents:UIControlEventTouchUpInside];
    m_iSwitch_QQ= [[UISwitch alloc] initWithFrame:CGRectMake(self.view.frame.size.width-120, 10, 70, 35)];
    m_iSwitch_QQ.tag = 104;
    [m_iSwitch_QQ addTarget:self action:@selector(changeiSwitch:) forControlEvents:UIControlEventTouchUpInside];
    m_oldname = @"";
}
- (void)viewWillDisappear:(BOOL)animated
{
    [m_BackBttBarItem removeFromSuperview];
    [m_settngBttBarItem removeFromSuperview];
}
- (void)viewWillAppear:(BOOL)animated
{
    if ([m_BackBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_BackBttBarItem];
    }
    if ([m_settngBttBarItem superview] == nil) {
        [self.navigationController.navigationBar addSubview:m_settngBttBarItem];
    }
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    [tMainTabBar.m_TabbarCustom removeFromSuperview];
    [self.view addSubview:tMainTabBar.m_TabbarCustom];
    if (isSend) {
        [self requestuserinfo];
    }
    NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
    [tUserDef synchronize];
    NSString* tBSinaStr = [tUserDef objectForKey:[NSString stringWithFormat:@"bangsina_%@",[tUserDef objectForKey:@"user_id"]]];
    if ([tBSinaStr isEqualToString:@"1"]&& [tBSinaStr length] > 0) {
        [m_iSwitch_SINA setOn:YES];
        m_iSwitch_SINA.userInteractionEnabled = NO;
    }else{
        [m_iSwitch_SINA setOn:NO];
    }
    NSString* tBSinaStr1 = [tUserDef objectForKey:[NSString stringWithFormat:@"bangqq_%@",[tUserDef objectForKey:@"user_id"]]];
    if ([tBSinaStr1 isEqualToString:@"1"]&& [tBSinaStr1 length] > 0) {
        [m_iSwitch_QQ setOn:YES];
        m_iSwitch_QQ.userInteractionEnabled = NO;
    }else{
        [m_iSwitch_QQ setOn:NO];
    }

}



- (void)navBackBtta
{
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabBar.m_TabbarCustom.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)navSettingBtt
{
    if (delegate!=nil) {
        [delegate Cleanup];
    }
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    [tMainTabBar registLogin];
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)requestuserinfo
{
    if (m_userid.length == 0 || m_pcode.length == 0) {
        sendtype = 2;
        return;
    }
    switch (sendtype) {
        case 0:
        {
            sendtype = 0;
            [[MyHttpProcessor sharedManager] RequestUesrNamePost:m_userid private_code:m_pcode name:m_name.text];
            [MyHttpProcessor sharedManager].delegate = self;
            break;
        }
        case 1:
        {
            sendtype = 1;
            [[MyHttpProcessor sharedManager] RequestUesrHaedPost:m_userid private_code:m_pcode haed:USERHAEDPATH];
            [MyHttpProcessor sharedManager].delegate = self;
            break;
        }
    }
    [self addHudLoad];
}
#pragma mark-
#pragma UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [m_DLCImagePicker CreateCamera];
            
        }else{
            NicknameSetViewController* iNickname = [[NicknameSetViewController alloc] init];
            iNickname.delegate = self;
            iNickname.navigationItem.hidesBackButton =YES;
            iNickname.nicktext = m_name.text;
            MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
            tMainTabBar.m_TabbarCustom.hidden = YES;
            [self.navigationController pushViewController:iNickname animated:YES];
            [iNickname release];
        }
    }else{
        
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if(section == 1){
        UIView* tSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
        [tSectionHeaderView setBackgroundColor:[UIColor colorWithRed:221/250.f green:224/255.0f blue:223/255.0f alpha:1.0]];
        UILabel* tLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 20)];
        [tLab setBackgroundColor:[UIColor clearColor]];
        [tLab setFont:[UIFont systemFontOfSize:18.0f]];
        [tLab setTextColor:[UIColor colorWithRed:125/250.f green:125/255.0f blue:125/255.0f alpha:1.0]];
        [tLab setText:@"绑定其他用户账号"];
        [tSectionHeaderView addSubview:tLab];
        [tLab release];
        return [tSectionHeaderView autorelease];
    }
    return nil;
}


#pragma mark-
#pragma UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else if(section == 1){
        return 60;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
#pragma mark-
#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString* tSStrCell = @"logincell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tSStrCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tSStrCell] autorelease];
        if (section == 0) {

             tCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(15, 13, 50, 20)];
            title.tag = 99;
            title.backgroundColor = [UIColor clearColor];
            title.font = [UIFont systemFontOfSize:14.0f];
            title.textColor = [UIColor colorWithRed:51/250.f green:51/255.0f blue:51/255.0f alpha:1.0];
            [tCell.contentView addSubview:title];
            [title release];
            
            if (row == 0) {
               
                m_headimage = [[AsyncImageView alloc] initWithFrame:CGRectMake(75, 5, 35, 35)];
                m_headimage.tag = 100;
                [m_headimage setBackgroundColor:[UIColor blackColor]];
                [tCell.contentView addSubview:m_headimage];
            }else{
                m_name = [[UILabel alloc] initWithFrame:CGRectMake(75, 13, 150, 20)];
                m_name.tag = 101;
                m_name.backgroundColor = [UIColor clearColor];
                m_name.font = [UIFont boldSystemFontOfSize:18.0f];
                m_name.textColor = [UIColor blackColor];
                [tCell.contentView addSubview:m_name];
                [m_name release];
            }
        }else{
            tCell.selectionStyle = UITableViewCellSelectionStyleNone;
            UILabel* iname = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 150, 20)];
            iname.tag = 102;
            iname.backgroundColor = [UIColor clearColor];
            iname.font = [UIFont systemFontOfSize:14.0f];
            iname.textColor = [UIColor colorWithRed:51/250.f green:51/255.0f blue:51/255.0f alpha:1.0];
            [tCell.contentView addSubview:iname];
            [iname release];
            if (row == 0) {

                [tCell.contentView addSubview:m_iSwitch_SINA];
            }else{

                [tCell.contentView addSubview:m_iSwitch_QQ];
            }
        }
    }
    
    if (section == 0) {
        if (row == 0) {
            UILabel* title = (UILabel*)[tCell viewWithTag:99];
            title.text = @"头像:";
            if (m_head_url != nil&&m_head_url != @"") {
                m_headimage._imageRequestURL = m_head_url;
                m_headimage.m_BoolSetImage = YES;
                [m_headimage customLoadImageFromURL];
            }else{
                [m_headimage SetUIImage:headimage];
            }

        }else{
            UILabel* title = (UILabel*)[tCell viewWithTag:99];
            title.text = @"昵称:";
            UILabel* namebel = (UILabel*)[tCell viewWithTag:101];
            namebel.text =name;
        }
    }
    else
    {
        if (row == 0) {
            UILabel* title = (UILabel*)[tCell viewWithTag:102];
            title.text = @"绑定新浪微博账号";

        }else{
            UILabel* title = (UILabel*)[tCell viewWithTag:102];
            title.text = @"绑定腾讯QQ账号";
        }
    }
    tCell.backgroundColor = [UIColor whiteColor];
    return tCell;
}

- (void)changeiSwitch:(id)_iSwitch
{
    UISwitch* iSwitch = (UISwitch*)_iSwitch;
    BOOL iSon = [iSwitch isOn];
    if (iSwitch.tag == 103) {
        m_type = 1;
        if (iSon) {
            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_userid target:@"sina"];
            [MyHttpProcessor sharedManager].delegate = self;
           
        }else{
//            [iSwitch setOn:YES animated:YES];
            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_userid target:@"sina"];
            [MyHttpProcessor sharedManager].delegate = self;
//            [[MyHttpProcessor sharedManager] RequestCancelInsurgentblog:m_userid target:@"sina"];
//            [MyHttpProcessor sharedManager].delegate = self;
        }
         [self addHudLoad];
    }else if (iSwitch.tag == 104){
        m_type = 2;
        if (iSon) {
            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_userid target:@"tencent"];
            [MyHttpProcessor sharedManager].delegate = self;
            
        }else{
//        [iSwitch setOn:YES animated:YES];
            [[MyHttpProcessor sharedManager] RequestInsurgentblog:m_userid target:@"tencent"];
            [MyHttpProcessor sharedManager].delegate = self;
            
//            [[MyHttpProcessor sharedManager] RequestCancelInsurgentblog:m_userid target:@"tencent"];
//            [MyHttpProcessor sharedManager].delegate = self;
        }
        [self addHudLoad];
    }
}

#pragma mark-
#pragma mark MyHttpProcessorDelegate
- (void)OutUpdataHaed:(NSString *)_data
{
    [self hudWasHidden:nil];
    if (_data.intValue == 1) {
        if (delegate != nil) {
          
            
            [delegate ModifyHaedText:m_chaeding];
        }
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"修改成功" isCue:NO delayTime:1.5f];
//        [self performSelector:@selector(popview) withObject:nil afterDelay:2.0f];
         m_oldhaedimg = nil;
        m_chaeding = nil;
        [self deleteImage:USERHAEDPATH];
    }
    isSend = NO;
    sendtype = 2;
}
- (void)OutUpdataName:(NSString *)_data
{
    [self hudWasHidden:nil];
    if (_data.intValue == 1) {
        if (delegate != nil) {
            [delegate ModifyNameText:m_name.text];
        }
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"修改成功" isCue:NO delayTime:1.5f];
//        [self performSelector:@selector(popview) withObject:nil afterDelay:2.0f];
    }
    isSend = NO;
    sendtype = 2;
}
- (void)OutInsurgentblog:(NSDictionary *)dic
{
     [self hudWasHidden:nil];
    NSString* result = [dic objectForKey:@"result"];
    if (result.integerValue == 1) {
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"已经绑定" isCue:YES delayTime:2.0f];
        [self hudWasHidden:nil];
    }else{
        WebViewController* tNextVC = [[WebViewController alloc] init];
        tNextVC.m_CallString = [dic objectForKey:@"callback"];
        tNextVC.m_RequestString =[dic objectForKey:@"auth"];
        tNextVC.navigationItem.hidesBackButton =YES;
        [self.navigationController pushViewController:tNextVC animated:YES];
        [tNextVC release];
    }
}
- (void)OutCInsurgentblog:(NSDictionary *)dic
{
    [self hudWasHidden:nil];
    NSString* result = [dic objectForKey:@"result"];
    if (result.integerValue == 1) {
        
    }else{
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        [tAppDel showWithCustomView:@"提示" detailText:@"解绑失败" isCue:YES delayTime:2.0f];
        [self hudWasHidden:nil];
        if (m_type == 1) {
            [m_iSwitch_SINA setOn:NO];
        }else{
            [m_iSwitch_QQ setOn:YES];
        }
        m_type = 0;
    }
}
- (void)OurErrer:(NSDictionary*)dic
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:[dic objectForKey:@"errorMsg"] isCue:YES delayTime:3.0f];
    [self hudWasHidden:nil];
    if (sendtype == 0) {
        [m_name setText:m_oldname];
    }
    else if(sendtype == 1)
    {
        [m_headimage SetUIImage:m_oldhaedimg];
        [self deleteImage:USERHAEDPATH]; 
    }
    isSend = NO;
}

- (void)popview
{
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabBar.m_TabbarCustom.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark DLCImagePickerController
- (void)GatimagePickerController:(UIImage *)_image picker:(UIImagePickerController *)_picker
{
    [m_headimage SetUIImage:_image];
    m_chaeding = _image;
    [self deleteImage:USERHAEDPATH];
    [self writeImage:_image toFileAtPath:USERHAEDPATH];
    sendtype = 1;
    isSend = YES;
    [_picker dismissModalViewControllerAnimated:YES];
    
}

#pragma mark-
#pragma NicknameSetDelegate
- (void)GetText:(NSString *)text
{
    if (![m_name.text isEqualToString:text]) {
        m_oldname = m_name.text;
        [m_name setText:text];

        sendtype = 0;
        isSend = YES;
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    m_MBHUD.delegate = nil;
	[m_MBHUD removeFromSuperview];
	[m_MBHUD release];
	m_MBHUD=nil;
}

-(void) addHudLoad{
	if (m_MBHUD == nil) {
		m_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:m_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		m_MBHUD.delegate = self;
		m_MBHUD.labelText = @"请求数据中...";
		[m_MBHUD show:YES];
	}
}

#pragma mark -
#pragma mark writAnddelete
- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath

{
    
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
    {
        return NO;
    }
    @try
    
    {
        NSData *imageData = nil;
        //        NSString *ext = [aPath pathExtension];
        // the rest, we write to jpeg
        
        // 0. best, 1. lost. about compress.
        
        imageData = UIImageJPEGRepresentation(image, 0);
        
        if ((imageData == nil) || ([imageData length] <= 0))
        {
            return NO;
        }
        [imageData writeToFile:aPath atomically:YES];
        return YES;
    }
    @catch (NSException *e)
    
    {
        NSLog(@"create thumbnail exception.");
        
    }
    return NO;
}

- (BOOL)deleteImage:(NSString*)aPath
{
    if ((aPath == nil) || ([aPath isEqualToString:@""]))
    {
        return NO;
    }
	NSFileManager *fm = [NSFileManager defaultManager];
	NSError *error;
    if (![fm fileExistsAtPath:aPath]) {
        return NO;
    }
	if(![fm removeItemAtPath:aPath error:&error])
	{
		NSLog(@"%@ can not be removed because:%@", aPath, error);
        return NO;
	}else{
        return YES;
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{

    [m_BackBttBarItem release];
    [m_settngBttBarItem release];
    [m_DLCImagePicker release];
    [m_TableView release];
    m_userid  = nil;
    m_pcode =nil;
    m_oldname = nil;
    m_oldhaedimg = nil;
    m_chaeding = nil;
    m_head_url = nil;
    [m_iSwitch_SINA release];
    [m_iSwitch_QQ release];
    [MyHttpProcessor sharedManager].delegate = nil;
    [super dealloc];
}
@end
